package com.zsummer.demo.rabbitmq.publishsubscribe;

import com.rabbitmq.client.*;
import com.zsummer.demo.rabbitmq.common.util.RabbitmqUtils;

import java.io.IOException;

/**
 * @author zsummer
 * @since 2021/12/9
 */
public class Consumer1 {

    public static void main(String[] args) throws Exception {
        // 获取连接
        Connection connection = RabbitmqUtils.getConnection();
        // 获取通道
        Channel channel = connection.createChannel();
        // 声明临时队列
        String queue = channel.queueDeclare().getQueue();
        /**
         * 绑定队列和交换机
         * 参数1：队列名称
         * 参数2：交换机名称
         * 参数3：路由键
         */
        channel.queueBind(queue, "logs", "");
        /**
         * 消费消息
         * 参数1：队列名称
         * 参数2：是否自动确认：false情况下使用channel.basicAck(envelope.getDeliveryTag(), false)手动确认
         * 参数3：消费消息
         */
        /**
         * 参数2的作用：In order to make sure a message is never lost,
         * RabbitMQ supports message acknowledgments.
         * An acknowledgement is sent back by the consumer to tell RabbitMQ that a particular message has been received,
         * processed and that RabbitMQ is free to delete it.
         */
        channel.basicConsume(queue, false, new DefaultConsumer(channel){
            /**
             * @param consumerTag 消费标识
             * @param envelope 信封，包含消息信息
             * @param properties 属性
             * @param body 消息
             * @throws IOException
             */
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("consumer1 " + new String(body));
                // 手动确认
                channel.basicAck(envelope.getDeliveryTag(), false);
            }
        });
    }
}
